#!/bin/bash

# Gitea 安装脚本 - CentOS 7.6
# 作者: Auto Generated
# 日期: $(date +%Y-%m-%d)
# 描述: 自动安装和配置 Gitea Git 服务

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
GITEA_VERSION="1.21.3"
GITEA_USER="git"
GITEA_HOME="/home/git"
GITEA_WORK_DIR="/var/lib/gitea"
GITEA_CUSTOM_DIR="/etc/gitea"
GITEA_LOG_DIR="/var/log/gitea"
GITEA_PORT="3000"
DB_TYPE="mysql"
DB_HOST="127.0.0.1:3306"
DB_NAME="gitea"
DB_USER="gitea"
DB_PASS="gitea123"

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要root权限运行"
        exit 1
    fi
}

# 检查系统版本
check_system() {
    log_step "检查系统版本..."
    if [[ ! -f /etc/redhat-release ]]; then
        log_error "此脚本仅支持 CentOS/RHEL 系统"
        exit 1
    fi
    
    local version=$(cat /etc/redhat-release)
    log_info "系统版本: $version"
    
    if ! echo "$version" | grep -q "CentOS.*7"; then
        log_warn "此脚本专为 CentOS 7.6 设计，其他版本可能存在兼容性问题"
        read -p "是否继续安装? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 更新系统
update_system() {
    log_step "更新系统包..."
    yum update -y
    yum install -y wget curl git tar
}

# 安装依赖
install_dependencies() {
    log_step "安装依赖包..."
    
    # 安装 EPEL 仓库
    yum install -y epel-release
    
    # 安装基础依赖
    yum install -y \
        wget \
        curl \
        git \
        tar \
        sqlite \
        which \
        systemd
}

# 安装 MySQL
install_mysql() {
    log_step "安装 MySQL..."
    
    if ! command -v mysql &> /dev/null; then
        # 安装 MySQL 5.7
        wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm
        rpm -ivh mysql57-community-release-el7-11.noarch.rpm
        yum install -y mysql-server
        
        # 启动 MySQL
        systemctl start mysqld
        systemctl enable mysqld
        
        # 获取临时密码
        local temp_password=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
        log_info "MySQL 临时密码: $temp_password"
        
        # 设置 MySQL
        log_warn "请手动执行以下命令设置 MySQL:"
        echo "mysql -u root -p'$temp_password' --connect-expired-password"
        echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'Root123!';"
        echo "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
        echo "CREATE USER '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
        echo "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';"
        echo "FLUSH PRIVILEGES;"
        echo "EXIT;"
        
        read -p "MySQL 设置完成后按回车继续..."
    else
        log_info "MySQL 已安装"
    fi
}

# 创建 Gitea 用户
create_gitea_user() {
    log_step "创建 Gitea 用户..."
    
    if ! id "$GITEA_USER" &>/dev/null; then
        useradd --system --shell /bin/bash --home-dir "$GITEA_HOME" --create-home "$GITEA_USER"
        log_info "用户 $GITEA_USER 创建成功"
    else
        log_info "用户 $GITEA_USER 已存在"
    fi
}

# 创建目录结构
create_directories() {
    log_step "创建目录结构..."
    
    mkdir -p "$GITEA_WORK_DIR"/{custom,data,log}
    mkdir -p "$GITEA_CUSTOM_DIR"
    mkdir -p "$GITEA_LOG_DIR"
    
    chown -R "$GITEA_USER:$GITEA_USER" "$GITEA_WORK_DIR"
    chown -R "$GITEA_USER:$GITEA_USER" "$GITEA_CUSTOM_DIR"
    chown -R "$GITEA_USER:$GITEA_USER" "$GITEA_LOG_DIR"
    chown -R "$GITEA_USER:$GITEA_USER" "$GITEA_HOME"
    
    chmod 750 "$GITEA_WORK_DIR"
    chmod 750 "$GITEA_CUSTOM_DIR"
    chmod 750 "$GITEA_LOG_DIR"
}

# 下载 Gitea
download_gitea() {
    log_step "下载 Gitea $GITEA_VERSION..."
    
    local download_url="https://dl.gitea.io/gitea/$GITEA_VERSION/gitea-$GITEA_VERSION-linux-amd64"
    
    cd /tmp
    wget -O gitea "$download_url"
    
    if [[ ! -f gitea ]]; then
        log_error "Gitea 下载失败"
        exit 1
    fi
    
    chmod +x gitea
    mv gitea /usr/local/bin/
    
    log_info "Gitea 下载完成"
}

# 创建配置文件
create_config() {
    log_step "创建 Gitea 配置文件..."
    
    cat > "$GITEA_CUSTOM_DIR/app.ini" << EOF
APP_NAME = Gitea: Git with a cup of tea
RUN_MODE = prod
RUN_USER = $GITEA_USER

[repository]
ROOT = $GITEA_WORK_DIR/repositories

[repository.local]
LOCAL_COPY_PATH = $GITEA_WORK_DIR/tmp/local-repo

[repository.upload]
TEMP_PATH = $GITEA_WORK_DIR/uploads

[server]
APP_DATA_PATH    = $GITEA_WORK_DIR/data
DOMAIN           = localhost
HTTP_PORT        = $GITEA_PORT
ROOT_URL         = http://localhost:$GITEA_PORT/
DISABLE_SSH      = false
SSH_PORT         = 22
SSH_LISTEN_PORT  = 22
LFS_START_SERVER = true
LFS_CONTENT_PATH = $GITEA_WORK_DIR/data/lfs
LFS_JWT_SECRET   = $(openssl rand -base64 32)
OFFLINE_MODE     = false

[database]
PATH     = $GITEA_WORK_DIR/data/gitea.db
DB_TYPE  = $DB_TYPE
HOST     = $DB_HOST
NAME     = $DB_NAME
USER     = $DB_USER
PASSWD   = $DB_PASS
LOG_SQL  = false
CHARSET  = utf8mb4

[indexer]
ISSUE_INDEXER_PATH = $GITEA_WORK_DIR/indexers/issues.bleve

[session]
PROVIDER_CONFIG = $GITEA_WORK_DIR/data/sessions
PROVIDER        = file

[picture]
AVATAR_UPLOAD_PATH            = $GITEA_WORK_DIR/data/avatars
REPOSITORY_AVATAR_UPLOAD_PATH = $GITEA_WORK_DIR/data/repo-avatars

[attachment]
PATH = $GITEA_WORK_DIR/data/attachments

[log]
MODE      = console
LEVEL     = info
ROUTER    = console
ROOT_PATH = $GITEA_LOG_DIR

[security]
INSTALL_LOCK   = false
SECRET_KEY     = $(openssl rand -base64 32)
INTERNAL_TOKEN = $(openssl rand -base64 32)

[service]
DISABLE_REGISTRATION              = false
ALLOW_ONLY_EXTERNAL_REGISTRATION  = false
REQUIRE_SIGNIN_VIEW               = false
REGISTER_EMAIL_CONFIRM            = false
ENABLE_NOTIFY_MAIL                = false
ENABLE_REVERSE_PROXY_AUTHENTICATION = false
ENABLE_REVERSE_PROXY_AUTO_REGISTRATION = false
ENABLE_CAPTCHA                    = false

[oauth2]
JWT_SECRET = $(openssl rand -base64 32)

[mailer]
ENABLED = false

[openid]
ENABLE_OPENID_SIGNIN = true
ENABLE_OPENID_SIGNUP = true
EOF

    chown "$GITEA_USER:$GITEA_USER" "$GITEA_CUSTOM_DIR/app.ini"
    chmod 640 "$GITEA_CUSTOM_DIR/app.ini"
    
    log_info "配置文件创建完成"
}

# 创建 systemd 服务
create_systemd_service() {
    log_step "创建 systemd 服务..."
    
    cat > /etc/systemd/system/gitea.service << EOF
[Unit]
Description=Gitea (Git with a cup of tea)
After=syslog.target
After=network.target
After=mysqld.service

[Service]
RestartSec=2s
Type=simple
User=$GITEA_USER
Group=$GITEA_USER
WorkingDirectory=$GITEA_WORK_DIR
ExecStart=/usr/local/bin/gitea web --config $GITEA_CUSTOM_DIR/app.ini
Restart=always
Environment=USER=$GITEA_USER HOME=$GITEA_HOME GITEA_WORK_DIR=$GITEA_WORK_DIR

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable gitea
    
    log_info "systemd 服务创建完成"
}

# 配置防火墙
configure_firewall() {
    log_step "配置防火墙..."
    
    if systemctl is-active --quiet firewalld; then
        firewall-cmd --permanent --add-port=$GITEA_PORT/tcp
        firewall-cmd --permanent --add-service=ssh
        firewall-cmd --reload
        log_info "防火墙配置完成"
    else
        log_warn "firewalld 未运行，跳过防火墙配置"
    fi
}

# 启动服务
start_gitea() {
    log_step "启动 Gitea 服务..."
    
    systemctl start gitea
    
    if systemctl is-active --quiet gitea; then
        log_info "Gitea 服务启动成功"
    else
        log_error "Gitea 服务启动失败"
        systemctl status gitea
        exit 1
    fi
}

# 显示安装信息
show_info() {
    log_step "安装完成！"
    echo
    log_info "Gitea 安装信息:"
    echo "  - 访问地址: http://$(hostname -I | awk '{print $1}'):$GITEA_PORT"
    echo "  - 配置文件: $GITEA_CUSTOM_DIR/app.ini"
    echo "  - 数据目录: $GITEA_WORK_DIR"
    echo "  - 日志目录: $GITEA_LOG_DIR"
    echo "  - 服务用户: $GITEA_USER"
    echo
    log_info "常用命令:"
    echo "  - 启动服务: systemctl start gitea"
    echo "  - 停止服务: systemctl stop gitea"
    echo "  - 重启服务: systemctl restart gitea"
    echo "  - 查看状态: systemctl status gitea"
    echo "  - 查看日志: journalctl -u gitea -f"
    echo
    log_warn "请在浏览器中访问 Gitea 完成初始化设置"
}

# 主函数
main() {
    log_info "开始安装 Gitea $GITEA_VERSION on CentOS 7.6"
    echo
    
    check_root
    check_system
    update_system
    install_dependencies
    install_mysql
    create_gitea_user
    create_directories
    download_gitea
    create_config
    create_systemd_service
    configure_firewall
    start_gitea
    show_info
    
    log_info "Gitea 安装完成！"
}

# 执行主函数
main "$@"
